package com.hq.ims.data.service;

import com.hq.ims.data.dao.PermissionMapAuthorityRoleMapper;
import com.hq.ims.data.entity.PermissionAuthority;
import com.hq.ims.data.entity.PermissionMapAuthorityRole;
import com.hq.ims.data.utils.ErrMsgConstant;
import com.hq.ims.data.vo.PermissionMapAuthorityRoleMapstruct;
import com.hq.ims.data.vo.PermissionRoleMapstruct;
import com.hq.mybatis.base.BaseService;
import com.hq.utils.util.ListUtils;
import com.hq.utils.util.ObjectUtils;
import com.hq.utils.util.StringUtils;
import com.hq.web.utils.SpringBootValidateUtils;
import lombok.NonNull;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * jiang bai ping
 *
 * @Email 526666031@qq.com
 * @Detail 权限组-角色映射表服务实现类
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class BasePermissionMapAuthorityRoleService extends BaseService<PermissionMapAuthorityRoleMapper, PermissionMapAuthorityRole> {

    @Resource
    private BasePermissionAuthorityService basePermissionAuthorityService;

    @Resource
    private BasePermissionRoleService basePermissionRoleService;

    @Resource
    private BasePermissionMapAuthorityUserService basePermissionMapAuthorityUserService;

    @Resource
    private BasePermissionMapRoleUserService basePermissionMapRoleUserService;

    @Resource
    private BaseUserService baseUserService;

    @Resource
    private BasePermissionMapAuthorityMenuService basePermissionMapRoleMenuService;
    @Resource
    private BasePermissionMenuService basePermissionMenuService;


    /**
     * 绑定角色权限
     */
    @Transactional(rollbackFor = Exception.class)
    public void bindRoleAuth(PermissionMapAuthorityRoleMapstruct.BindRoleAuthVo saveVo) {

        SpringBootValidateUtils.validate(saveVo);
        PermissionRoleMapstruct.PermissionRoleVo permissionRoleVo = basePermissionRoleService.getByRoleIdAndCompanyId(saveVo.getPermissionRoleId(), saveVo.getCompanyId());
        ObjectUtils.isNullThrow(permissionRoleVo, ErrMsgConstant.PERMISSION_ROLE_NOT_EXISTS);

        //1.删除旧数据
        this.delByRoleId(saveVo.getPermissionRoleId());

        //2.保存新数据
        List<PermissionMapAuthorityRole> saveList = new ArrayList<>();
        List<String> authIdList = saveVo.getPermissionAuthorityIdList().stream().distinct().collect(Collectors.toList());
        authIdList.forEach(authId -> {
            PermissionMapAuthorityRole permissionMapAuthorityRole = new PermissionMapAuthorityRole();
            saveList.add(permissionMapAuthorityRole);
            //检查映射关系是否存在重复情况
            permissionMapAuthorityRole.setPermissionRoleId(saveVo.getPermissionRoleId());
            permissionMapAuthorityRole.setPermissionAuthorityId(authId);
            permissionMapAuthorityRole.setCompanyId(saveVo.getCompanyId());
        });

        if (ListUtils.isExistsEle(saveList)) {
            this.saveBatch(saveList);
        }
    }

    /**
     * 绑定权限角色
     */
    @Transactional(rollbackFor = Exception.class)
    public void bindAuthRole(PermissionMapAuthorityRoleMapstruct.BindAuthRoleVo saveVo) {

        SpringBootValidateUtils.validate(saveVo);
        PermissionAuthority permissionAuthority = basePermissionAuthorityService.getAuthByAuthIdAndCompanyId(saveVo.getPermissionAuthorityId(), saveVo.getCompanyId());
        ObjectUtils.isNullThrow(permissionAuthority, ErrMsgConstant.PERMISSION_AUTH_NOT_EXISTS);

        //1.删除旧数据
        this.delByAuthId(saveVo.getPermissionAuthorityId());

        //2.保存新数据
        List<PermissionMapAuthorityRole> saveList = new ArrayList<>();
        List<String> roleIdList = saveVo.getPermissionRoleIdList().stream().distinct().collect(Collectors.toList());
        roleIdList.forEach(roleId -> {
            PermissionMapAuthorityRole permissionMapAuthorityRole = new PermissionMapAuthorityRole();
            saveList.add(permissionMapAuthorityRole);
            //检查映射关系是否存在重复情况
            permissionMapAuthorityRole.setPermissionRoleId(roleId);
            permissionMapAuthorityRole.setPermissionAuthorityId(saveVo.getPermissionAuthorityId());
            permissionMapAuthorityRole.setCompanyId(saveVo.getCompanyId());
        });

        if (ListUtils.isExistsEle(saveList)) {
            this.saveBatch(saveList);
        }
    }

    /**
     * 检查重复添加的情况
     *
     * @param permissionMapGroupRole 参数
     */
    public boolean checkMapAuthRoleIsRepeat(PermissionMapAuthorityRole permissionMapGroupRole) {

        StringUtils.verificationEmpty(permissionMapGroupRole.getPermissionAuthorityId(), "权限组不能为空");
        StringUtils.verificationEmpty(permissionMapGroupRole.getPermissionRoleId(), "角色不能为空");

        return this.lambdaQuery()
                .eq(StringUtils.isNotEmpty(permissionMapGroupRole.getCompanyId()), PermissionMapAuthorityRole::getCompanyId, permissionMapGroupRole.getCompanyId())
                .eq(PermissionMapAuthorityRole::getPermissionAuthorityId, permissionMapGroupRole.getPermissionAuthorityId())
                .eq(PermissionMapAuthorityRole::getPermissionRoleId, permissionMapGroupRole.getPermissionRoleId())
                .count() > 0;

    }

    /**
     * 删除权限-角色的映射关系根据组id
     *
     * @param authId 组ID
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean delByAuthId(
            String authId
    ) {
        StringUtils.verificationEmpty(authId, "组ID不能为空");
        //校验组id是否存在
        return this.lambdaUpdate().eq(PermissionMapAuthorityRole::getPermissionAuthorityId, authId).remove();
    }

    /**
     * 根据角色id 删除组中相关数据
     */
    @Transactional(rollbackFor = Exception.class)
    public void delByRoleId(String roleId) {
        this.lambdaUpdate().eq(PermissionMapAuthorityRole::getPermissionRoleId, roleId).remove();
    }


    //------------------------------ 查询 ----------------------------------

    public List<PermissionMapAuthorityRole> getByAuthIdList(@NonNull List<String> authIdList) {
        List<PermissionMapAuthorityRole> permissionMapAuthorityRoleList = this.lambdaQuery()
                .in(PermissionMapAuthorityRole::getPermissionAuthorityId, authIdList)
                .orderByAsc(PermissionMapAuthorityRole::getCreateDateTime)
                .list();
        return permissionMapAuthorityRoleList;
    }

    public List<PermissionMapAuthorityRole> getByRoleIdList(@NonNull List<String> roleIdList) {
        List<PermissionMapAuthorityRole> permissionMapAuthorityRoleList = this.lambdaQuery()
                .in(PermissionMapAuthorityRole::getPermissionRoleId, roleIdList)
                .orderByAsc(PermissionMapAuthorityRole::getCreateDateTime)
                .list();
        return permissionMapAuthorityRoleList;
    }


    /**
     * 根据组ID获取所有角色
     *
     * @param authIdList 组id
     */
    public List<String> getRoleIdListByAuthIdList(@NonNull List<String> authIdList) {
        List<PermissionMapAuthorityRole> groupRoles = this.lambdaQuery()
                .select(PermissionMapAuthorityRole::getPermissionRoleId)
                .in(PermissionMapAuthorityRole::getPermissionAuthorityId, authIdList)
                .orderByAsc(PermissionMapAuthorityRole::getCreateDateTime)
                .list();
        if (ListUtils.isNotExistsEle(groupRoles)) {
            return ListUtils.newEmptyList();
        }
        return groupRoles.stream().map(PermissionMapAuthorityRole::getPermissionRoleId).distinct().collect(Collectors.toList());
    }

    /**
     * 根据组ID获取所有角色
     */
    public List<String> getAuthIdListByRoleIdList(@NonNull List<String> roleIdList) {
        if (ListUtils.isNotExistsEle(roleIdList)) {
            return ListUtils.newEmptyList();
        }
        List<PermissionMapAuthorityRole> groupRoles = this.lambdaQuery()
                .select(PermissionMapAuthorityRole::getPermissionAuthorityId)
                .in(PermissionMapAuthorityRole::getPermissionRoleId, roleIdList)
                .orderByAsc(PermissionMapAuthorityRole::getCreateDateTime)
                .list();
        if (ListUtils.isNotExistsEle(groupRoles)) {
            return ListUtils.newEmptyList();
        }
        return groupRoles.stream().map(PermissionMapAuthorityRole::getPermissionAuthorityId).distinct().collect(Collectors.toList());
    }

    @Transactional(rollbackFor = Exception.class)
    public void delByCompanyId(String companyId) {
        this.lambdaUpdate().eq(PermissionMapAuthorityRole::getCompanyId,companyId).remove();
    }
}
